<?php
$defineNamespace$

class $controllerName$Controller extends \Phalcon\Mvc\Controller
{
	/**
	 * Index action
	 */
	public function indexAction()
	{
		$page = $this->request->get('page', 'int', 1);
		$data = $this->request->get();
		$this->view->setVar("form", $data);

		$item = new $rootFullModelName$();
		$this->view->item = $item;

		$criteria = \Phalcon\Mvc\Model\Criteria::fromInput($this->di, '$fullModelName$', $data);
		$where = $criteria->getWhere();

		$query = $this->modelsManager->createBuilder()->from('$fullModelName$');

		if ($where) {
			$query->andwhere($where, $criteria->getParams()['bind']);
		}

		$query->orderBy('$pk$ desc');

		$paginator = new \Phalcon\Paginator\Adapter\QueryBuilder(array(
			"builder" => $query,
			"limit" => 30,
			"page" => $page
		));

		$this->view->setVar("page", $paginator->getPaginate());
	}

	/**
	 * Displays the creation form
	 */
	public function newAction()
	{
		$this->view->pick("$viewpath$form");
		$item = new $rootFullModelName$();
		$this->view->item = $item;

		if (!$this->request->isPost()) {
			return;
		}

		$item->assign($this->request->getPost());

		if (!$item->save()) {
			foreach ($item->getMessages() as $message) {
				$this->flash->error($message);
			}

			return $this->response->redirect('$uri$/index');
		}

		$this->flash->success("Created successfully");

		return $this->response->redirect('$uri$/index');
	}

	/**
	 * Edits a $modelName$
	 *
	 * @param string $pkVar$
	 */
	public function editAction($pkVar$)
	{
		$this->view->pick("$viewpath$form");
		$item = $rootFullModelName$::findFirstBy$pk$($pkVar$);
		if (!$item) {
			$this->flash->error("Not found");

			return $this->response->redirect('$uri$/index');
		}

		$this->view->item = $item;

		if (!$this->request->isPost()) {
			return;
		}

		$item->assign($this->request->getPost());

		if (!$item->save()) {

			foreach ($item->getMessages() as $message) {
				$this->flash->error($message);
			}

			return;
		}

		$this->flash->success("Updated successfully");

		return $this->response->redirect('$uri$/index');
	}

	/**
	 * Deletes a $modelName$
	 *
	 * @param string $pkVar$
	 */
	public function delAction($pkVar$)
	{
		$item = $rootFullModelName$::findFirstBy$pk$($pkVar$);
		if (!$item) {
			$this->flash->error("Not found");

			return $this->response->redirect('$uri$/index');
		}

		if (!$item->delete()) {

			foreach ($item->getMessages() as $message) {
				$this->flash->error($message);
			}

			return $this->response->redirect('$uri$/index');
		}

		$this->flash->success("Deleted successfully");

		return $this->response->redirect('$uri$/index');
	}

}
